package com.llkj.qingnianguoxue.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.ShopCartAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.bean.HotRankingBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.llkj.qingnianguoxue.mine.PayOrderActivity.REQUEST_ORDER_PAY;

/**
 * 购物车
 */
public class ShopCartActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener{

    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView lvCart;
    private ShopCartAdapter shopCartAdapter;
    private List<HotRankingBean.RankingBean> mShopCartData;
    private double mTotalMoney;//总金额
    private int mShopCount;//商品数量
    @BindView(R.id.rl_bottom)
    RelativeLayout rlBottom;//底部
    @BindView(R.id.ll_check_all)
    LinearLayout llCheckAll;//全部选择
    @BindView(R.id.tv_total)
    TextView tvTotalMoney;//商品数量
    @BindView(R.id.tv_pay)
    TextView btnPay;//结算
    private int totalSize, mPage, mCurrentPosition;
    private String mCartIds;//结算id
    private String mBuyCartIds = "",mDelCartIds = "";//用于判断在当前界面处理的商品

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_cart);
        setTitle("购物车", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, -1, -1);
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        ButterKnife.bind(this);

        initView();
        initListener();

        onRefresh();
    }

    private void initView() {
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvCart.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mShopCartData = new ArrayList<>();
        shopCartAdapter = new ShopCartAdapter(R.layout.item_shop_cart, mShopCartData);
        lvCart.setAdapter(shopCartAdapter);
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(this);
        shopCartAdapter.setOnLoadMoreListener(this);
        lvCart.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if(view.getId() == R.id.iv_check){
                    clickCheckView(i);
                }else if(view.getId() == R.id.tvDelItem){
                    mCurrentPosition = i;
                    dialogConfirm("您要删除该物品吗？", null, "取消", "删除").show();
                }
            }
        });

    }

    @Override
    protected void leftDoWhat() {
        super.leftDoWhat();
        backWithResult();
    }

    @OnClick({R.id.ll_check_all, R.id.tv_pay})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_check_all://全选
                if (llCheckAll.isSelected()) {
                    llCheckAll.setSelected(false);
                } else {
                    llCheckAll.setSelected(true);
                }

                setCheckAllState(llCheckAll.isSelected());
                break;
            case R.id.tv_pay://结算
                if(mShopCartData.size()==0){
                    ToastUtil.makeLongText(this,"您没有要结算的商品");
                    return;
                }
                if(mTotalMoney<=0){
                    ToastUtil.makeLongText(this,"请选择要结算的商品");
                    return;
                }

                List<HotRankingBean.RankingBean> checkShopsData = new ArrayList<>();
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < mShopCartData.size(); i++) {
                    HotRankingBean.RankingBean cartBean = mShopCartData.get(i);
                    if (cartBean.isCheck()) {
                        checkShopsData.add(cartBean);
                        stringBuilder.append(cartBean.getId());
                        stringBuilder.append(",");
                    }
                }
                if(stringBuilder.length()>1){
                    mCartIds = stringBuilder.toString().substring(0,stringBuilder.length()-1);
                }

                Bundle bundle = new Bundle();
                bundle.putSerializable("checkShops", (Serializable) checkShopsData);
                bundle.putString("shopsId",mCartIds);
                bundle.putFloat("payMoney",(float) mTotalMoney);
                bundle.putString("categoryType","shopCart");
                startActivityForResult(PayOrderActivity.class,bundle,REQUEST_ORDER_PAY);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK && requestCode==REQUEST_ORDER_PAY){
            onRefresh();
        }
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        HotRankingBean.RankingBean item = mShopCartData.get(mCurrentPosition);
        loadWaitDialog();//删除购物车
        HttpMethod.delShopping(this, this, item.getId(),"2");
    }

    /**
     * 设置是否全部选中
     *
     * @param isCheck
     */
    private void setCheckAllState(boolean isCheck) {
        mTotalMoney = 0;
        mShopCount = 0;
        for (int i = 0; i < mShopCartData.size(); i++) {
            HotRankingBean.RankingBean cartBean = mShopCartData.get(i);
            cartBean.setIsCheck(isCheck);

            if (isCheck) {
                double price = 0;
                try {
                    price = Double.parseDouble(cartBean.getPrice());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mTotalMoney += price;
            }
        }
        shopCartAdapter.notifyDataSetChanged();

        if (isCheck) {
            mShopCount = mShopCartData.size();
        }
        setTotalView();
    }

    /**
     * 控制商品选择
     * @param position
     */
    private void clickCheckView(int position) {
        HotRankingBean.RankingBean cartBean = mShopCartData.get(position);

        cartBean.setIsCheck(!cartBean.isCheck());

        double price = 0;
        try {
            price = Double.parseDouble(cartBean.getPrice());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //计算金额数量
        if (cartBean.isCheck()) {
            mTotalMoney += price;
            mShopCount++;
        } else {
            mTotalMoney -= price;
            mShopCount--;
        }
        shopCartAdapter.notifyItemChanged(position);

        if (mShopCount == mShopCartData.size()) {//设置是否全部选中了
            llCheckAll.setSelected(true);
        } else {
            llCheckAll.setSelected(false);
        }

        setTotalView();
    }

    /**
     * 设置结算结果
     */
    private void setTotalView() {
        String money = String.format("%.2f", mTotalMoney);
        money = "合计:￥" + money;
//        SpannableString moneySpan = TextViewUtil.getForegroundColorSpan(this, money, 3, money.length(), getResources().getColor(R.color.colorB93A3C));
        tvTotalMoney.setText(money);
        btnPay.setText("结算(" + mShopCount + ")");
    }

    /**
     * 获取购物车数据
     */
    private void getCartData(){
        HttpMethod.userShopping(this, this, String.valueOf(mPage));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);

        if (method == HttpMethod.HTTP_USER_SHOPPING) {//8.12我的购物车
            HotRankingBean cartBean = GsonUtil.GsonToBean(data, HotRankingBean.class);
            if (cartBean != null) {
                totalSize = Integer.parseInt(cartBean.getNum());
                if (mPage == 1) {
                    mShopCartData.clear();
                    LoadDataHelper.refreshComplete(shopCartAdapter, mShopCartData, refreshLayout, lvCart);
                } else {
                    shopCartAdapter.setEnableLoadMore(true);
                    shopCartAdapter.loadMoreComplete();
                }
                mShopCartData.addAll(cartBean.getShopping());
                shopCartAdapter.notifyDataSetChanged();
            }
        } else if (method == HttpMethod.HTTP_USER_DEL_SHOPPING) {//8.13删除购物车商品
            delShopResult();
        }
//        else if (method == HttpMethod.HTTP_YOUR_URL) {//获取支付参数
//            Pingpp.createPayment(this, data);//调起支付控件
//        }
// else if(method == HttpMethod.HTTP_ORDER_ORDER_SHOPPING){//支付成功
//            ToastUtil.makeLongText(this,"购买成功");
//            mBuyCartIds = mBuyCartIds + mCartIds +",";
//            onRefresh();
//            mTotalMoney = 0;
//            mShopCount = 0;
//            llCheckAll.setSelected(false);
//            setTotalView();
//        }
    }

    /**
     * 删除商品后，购物车界面变化
     */
    private void delShopResult(){
        HotRankingBean.RankingBean cartBean = mShopCartData.get(mCurrentPosition);
        mDelCartIds = mDelCartIds + cartBean.getId()+",";//记录删除的
        boolean isCheck = cartBean.isCheck();
        double price = 0;
        try {
            price = Double.parseDouble(cartBean.getPrice());
        } catch (Exception e) {
            e.printStackTrace();
        }

        mShopCartData.remove(mCurrentPosition);
        shopCartAdapter.notifyDataSetChanged();
        if(isCheck){//是选中的商品，总额要变化，结算数还要变,还有全选状态要判断
            mTotalMoney -= price;
            mShopCount--;
        }
        if (mShopCount == mShopCartData.size()) {//设置是否全部选中了
            llCheckAll.setSelected(true);
        } else {
            llCheckAll.setSelected(false);
        }

        setTotalView();
    }
    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);

        if (!StringUtils.isEmpty(message)) {
            ToastUtil.makeLongText(this, message);
        }
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getCartData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getCartData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, shopCartAdapter, null, lvCart, totalSize);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backWithResult();
        }
        return false;
    }
    private void backWithResult(){
        if(mBuyCartIds.length()>1){
            mBuyCartIds= mBuyCartIds.substring(0,mBuyCartIds.length()-1);
        }
        if(mDelCartIds.length()>1){
            mDelCartIds = mDelCartIds.substring(0,mDelCartIds.length()-1);
        }
        Intent intent = new Intent();
        if(!StringUtils.isEmpty(mBuyCartIds)){
            intent.putExtra("result",mBuyCartIds);
        }

        if(!StringUtils.isEmpty(mDelCartIds)){
            intent.putExtra("del",mDelCartIds);
        }
        setResult(RESULT_OK,intent);
        finish();
    }
}
